package com.sf.ams.saxhandler;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.sf.ams.entity.Environment;
import com.sf.ams.entity.SystemInfo;
import com.sf.ams.entity.enums.ExecuteStatus;
import com.sf.ams.utils.StringUtil;

/**
 * 描述：
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年9月26日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
public class DataStoreAnalysisHandler extends DefaultHandler {

	private static Logger logger = LoggerFactory.getLogger(DataStoreAnalysisHandler.class);
	private SystemInfo system;
	private static List<SystemInfo> systems;
	private Environment environment;
	private List<Environment> environments;
	private String preTag;
	private DataStoreAnalysisHandler(){
		
	}
	private static class Singlon{
		private static DataStoreAnalysisHandler instance;
		static {
			instance = new DataStoreAnalysisHandler();
		}
		public static DataStoreAnalysisHandler getInstance() {
			return instance;
		}
	}
	public static DataStoreAnalysisHandler getInstance(){
		return Singlon.getInstance();
	}
	private  void analysisDataStore(){
//		InputStream inputStream = Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("/dataStore.xml");
//		if(inputStream == null) {
//			inputStream = DataStroeAnalysisHandler.class.getResourceAsStream("/dataStore.xml");
//		}
			SAXParserFactory factory = SAXParserFactory.newInstance();  
			InputStream inputStream = null;
	        try {
	        	SAXParser parser = factory.newSAXParser();
	        	//ResourceUtils.getFile(Constant.DATASTOREDIR)
	        	//inputStream = ClassUtils.getDefaultClassLoader().getResourceAsStream(Constant.DATASTOREDIR);
	        	inputStream = new FileInputStream(DataStoreManager.getInstance().getDataStoreXml()); 
				parser.parse(inputStream, new DataStoreAnalysisHandler());
			} catch (SAXException | IOException |ParserConfigurationException e) {
				logger.error("analysis DataStore xml error",e);
			} finally{
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
					}	
				}
				
			}
	}
	public  List<SystemInfo> getAllSystems() {
		analysisDataStore();
		return systems;
	}
	@Override
	public void startDocument() throws SAXException{
		systems = new ArrayList<>();
		environments = new ArrayList<>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if("system".equals(qName)){
			system = new SystemInfo();
		}
		if("environment".equals(qName)){
			environment = new Environment();
		}
		preTag = qName;
	}
	
	@Override
	@Transactional
	public void endElement(String uri, String localName, String qName)throws SAXException{
		if (system != null && "system".equals(qName)) {
			systems.add(system);
			system = null;
		}
		if (environment != null && "environment".equals(qName)) {
			//environment.setSystem(system);
			environments.add(environment);
			environment = null;
		}
		if (environments != null && "environments".equals(qName)) {
			system.setEnvironments(environments);
			environments = null;
			environments = new ArrayList<>();
		}
		preTag = null;
	}
	/**
	 * <systemCode>RPS</systemCode>
			<pathType>git</pathType>
			<pathAddress>http://734621@git.sf-express.com/scm/shiva-rps/shiva-rps-core.git</pathAddress>
			<gitUserName>734621</gitUserName>
			<gitPassword>123456</gitPassword>
			
			
			<environment>
					<environmentType>SIT</environmentType>
					<environmentIndex>1</environmentIndex>
					<dataBaseType>Mysql</dataBaseType>
					<dataBaseConnection>jdbc:mysql://10.202.15.39:3306/rpsdb?useUnicode=true&amp;characterEncoding=UTF8&amp;autoReconnect=true&amp;zeroDateTimeBehavior=convertToNull</dataBaseConnection>
					<dataBaseUserName>rps</dataBaseUserName>
					<dataBasePassword>rps123456</dataBasePassword>
					<currentIndex>2</currentIndex>
					<lastExecuteTime>2017-09-26 16:05:13</lastExecuteTime>
					<currentStatus>执行成功</currentStatus>
					<executeFailReason></executeFailReason>
				</environment>
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (system != null && preTag != null) {
			String data = new String(ch, start, length);
			data = data.trim();
			if ("systemCode".equals(preTag)) {
				system.setSystemCode(data);
			}
			if ("pathType".equals(preTag)) {
				system.setPathType(data);
			}
			if ("pathAddress".equals(preTag)) {
				system.setPathAddress(data);
			}
			if("gitUserName".equals(preTag)) {
				system.setGitUserName(data);
			}
			if ("gitPassword".equals(preTag)) {
				system.setGitPassword(data);
			}
			if("gitBranch".equals(preTag)) {
				system.setGitBranch(data);
			}
			if ("sqlPath".equals(preTag)) {
				system.setSqlPath(data);
			}
			if ("maxIndex".equals(preTag)) {
				system.setMaxIndex(Integer.valueOf(data));
			}
			if( environment != null ) {
				if ("environmentType".equals(preTag)){
					environment.setEnvironmentType(data);
				}
				if ("environmentIndex".equals(preTag)){
					environment.setEnvironmentIndex(Integer.valueOf(data));
				}
				if ("dataBaseType".equals(preTag)){
					environment.setDataBaseType(data);
				}
				if ("dataBaseConnection".equals(preTag)){
					environment.setDataBaseConnection(data);
				}
				if ("dataBaseUserName".equals(preTag)){
					environment.setDataBaseUserName(data);
				}
				if ("dataBasePassword".equals(preTag)){
					environment.setDataBasePassword(data);
				}
				if ("currentIndex".equals(preTag)){
					environment.setCurrentIndex(StringUtil.isEmpty(data)?null:Integer.valueOf(data));
				}
				if ("lastExecuteTime".equals(preTag)){
					environment.setLastExecuteTime(data);
				}
				if ("currentStatus".equals(preTag)){
					if("SUCCESS".equals(data)){
						environment.setCurrentStatus(ExecuteStatus.SUCCESS);
					} else if ("FAIL".equals(data)) {
						environment.setCurrentStatus(ExecuteStatus.FAIL);
					} else if("INIT".equals(data)) {
						environment.setCurrentStatus(ExecuteStatus.INIT);
					}
				}
				if ("executeFailReason".equals(preTag)){
					environment.setExecuteFailReason(data);
				}
			}
			
		}
	}


}
